//
//  LLComposeViewController.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/11/4.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SVProgressHUD

class LLComposeViewController: UIViewController {
    
    
    
    private var tooBarBottomCon: NSLayoutConstraint?
    
    private var photoSelectorViewBottomCon: NSLayoutConstraint?
    
    private let statusMaxLength = 20

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        prepareUI()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    func willChangeFrame(notification:NSNotification){
        print("notification:\(notification)")
        
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]as! NSTimeInterval
        
        tooBarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - endFrame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
//        
//        textView.inputView = view
//        view.backgroundColor = UIColor.redColor()
        
        if photoSelectorViewBottomCon?.constant != 0{
        
            textView.becomeFirstResponder()
        }
        
    }
    
    
    func prepareUI(){
        view.addSubview(textView)
        view.addSubview(PhotoSelectorVC.view)
        view.addSubview(toolBar)
        view.addSubview(lengthTipLabel)
        
        
        setNavigationBar()
        setUpTextView()
        preparePhotoSelectorView()
        setUpToolBar()
        prepareLengthTipLabel()
        
    }
    func setNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        setUpTitleView()
    
    }
    
    private func setUpToolBar(){
        
//        view.addSubview(toolBar)
        
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        
        tooBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
//        toolBar
        
        var items = [UIBarButtonItem]()
        
        // 每个item对应的图片名称
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        var index = 0
        for dict in itemSettings{
            
            let imageName = dict["imageName"]!
            
            let action = dict["action"]!
            
            let item = UIBarButtonItem(imageName: imageName)
            
            let button = item.customView as! UIButton
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
                index++
        }
        items.removeLast()
        toolBar.items = items
    }
    
    func prepareLengthTipLabel(){
        
//        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
    
    }
    
    private func preparePhotoSelectorView(){
        
        let photoSelectorView = PhotoSelectorVC.view
//        view.addSubview(photoSelectorView)
        
        
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false

        let views = ["psv" : photoSelectorView]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
        
//       view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
       photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.size.height * 0.6)
        
        view.addConstraint(photoSelectorViewBottomCon!)
    
    }
    
    
    func picture(){
        print("图片")
        photoSelectorViewBottomCon?.constant = 0
        
        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    func trend(){
        print("#")
    }
    
    func mention(){
        print("@")
    }
    
    func emoticon(){
        print("表情")
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    <#code to be executed after a specified delay#>
//});
        textView.resignFirstResponder()
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
            self.textView.becomeFirstResponder()
            
            
        }
    }
    func add(){
        print("加号")
    }
    
    
    private func setUpTextView(){
//        view.addSubview(textView)
    
        
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
    }
    
    
    func setUpTitleView(){
        let prefix = "发微博"
        
        if let name  = LLUserAccount.loadAccount()?.name{
            let titleName = prefix + "\n" + name
            
            let attrString = NSMutableAttributedString(string: titleName)
            
            let label = UILabel()
            
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            
            let nameRange = (titleName as NSString).rangeOfString(name)
            
            
            attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
            attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            
            
            label.attributedText = attrString
            label.sizeToFit()
            
            navigationItem.titleView = label
        }else{
            navigationItem.title = prefix
        }
        
    }
    
    @objc private func close(){
        
        textView.resignFirstResponder()
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func send(){
        
        print("__FUCNTION__")
        
        let text = textView.emoticonText()
        
        let statusLenght = text.characters.count
        
        if statusMaxLength - statusLenght < 0 {
            
            SVProgressHUD.showErrorWithStatus("微博長度過長", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        let image = PhotoSelectorVC.photos.first
        
        SVProgressHUD.showWithStatus("正在發送..", maskType: SVProgressHUDMaskType.Black)
        
        LLNetworkTools.sharedInstance.sendStatus(image, status: text) { (result, error) -> () in
            if error != nil{
                print("error:\(error)")
                
                SVProgressHUD.showErrorWithStatus("網絡不給力...", maskType: SVProgressHUDMaskType.Black)
                return
            }
            
           
                SVProgressHUD.showWithStatus("微博发送成功", maskType: SVProgressHUDMaskType.Black)
                
           
            
            self.close()
        }
        
    }
    
    
    private lazy var toolBar:UIToolbar = {
        let toolBar = UIToolbar()
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return toolBar
    }()
    
    private lazy var textView:LLPlaceholderTextView = {
        
        let textView = LLPlaceholderTextView()
        
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        textView.font = UIFont.systemFontOfSize(18)
        
        textView.backgroundColor = UIColor.brownColor()

        textView.textColor = UIColor.blackColor()
        
        textView.placeholder = "分享新鲜事...."
        
        textView.bounces = true
        textView.alwaysBounceVertical = true
        
//        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        textView.delegate = self
        
      return textView
    }()
    
    private lazy var emoticonVC:LLEmoticonViewController = {
    
        let controller = LLEmoticonViewController()
        
        controller.textView = self.textView
        
//       self.addChildViewController(controller)
        
    
        return controller
    }()
    
    private lazy var lengthTipLabel:UILabel = {
        let label = UILabel(fonsize: 12, textColoc: UIColor.lightGrayColor())
        
        label.text = String(self.statusMaxLength)
        
        return label
    }()
    
    private lazy var PhotoSelectorVC:LLPhotoSelectorViewController = {
        
        let vc = LLPhotoSelectorViewController()
        //让照片选择控制器被人管理，这样在需要的时候照片选择器不会被退出
       self.addChildViewController(vc)
        
        return vc
    }()
}


extension LLComposeViewController:  UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
        let statusLength = textView.emoticonText().characters.count
        
        let length = statusMaxLength - statusLength
        
        lengthTipLabel.text = String(length)
        
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }

}
